#!/usr/bin/env bash

export GD_API="https://api.godaddy.com"

___gdcurl() {
  curl -sSL \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: sso-key ${GD_Key}:${GD_Secret}" \
    $@
}

godaddy.getPeriod() {
  period=$1
  if [ -z "${period}" ]; then
    return 0
  fi

  if echo "${period}" | grep '[^0-9]' >>/dev/null; then
    return 0
  fi

  if [ "${period}" -lt 1 ]; then
    return 0
  fi

  echo ${period}
  return 1
}

godaddy.record() {
  echo 解析记录查询
  echo ------------------------
  domain=$1
  rsType=$2
  name=$3

  while [ -z "${domain}" ]; do
    echo -n "查询域名: "
    read domain
  done

  if [ -z "${rsType}" ]; then
    echo -n "域名类型: "
    read rsType
  fi

  if [ -z "${name}" ]; then
    echo -n "域名前缀: "
    read name
  fi

  if [ -z "${rsType}" ]; then
    echo
    ___gdcurl ${GD_API}/v1/domains/${domain}/records | jq '.[]'
    return 0
  fi

  if [ -z "${name}" ]; then
    echo
    ___gdcurl ${GD_API}/v1/domains/${domain}/records/${rsType} | jq '.[]'
    return 0
  fi

  echo
  ___gdcurl ${GD_API}/v1/domains/${domain}/records/${rsType}/${name} | jq '.[]'
}

godaddy.renew() {
  domain=$1
  period=$2

  echo 域名续费
  echo ------------------------
  while [ -z "${domain}" ]; do
    echo -n "续费域名: "
    read domain
  done

  while godaddy.getPeriod ${period}; do
    echo -n "续费年限: "
    read -n period
    echo
  done

  echo -n "续费域名 ${domain} -> ${period}年, 按'Y'确认: "
  read -n confirm_renew
  echo ${confirm_renew}

  case ${confirm_renew} in
  y | Y)
    echo
    echo 开始请求续费
    ___gdcurl -X POST -d "{\"period\": ${period}}" "${GD_API}/v1/domains/${domain}/renew" | jq
    ;;
  *)
    echo
    echo 取消续费
    ;;
  esac
}

godaddy.info() {
  echo 域名信息查询
  echo ------------------------
  domain=$1

  while [ -z "${domain}" ]; do
    echo -n "输入域名: "
    read domain
  done

  echo
  ___gdcurl "${GD_API}/v1/domains/${domain}" |
    jq '{domain: .domain, createdAt: .createdAt, expires: .expires, renewDeadline: .renewDeadline, status: .status}'
}

godaddy.list() {
  local q=$1
  echo 域名列表: ${q}
  echo ------------------------
  echo
  ___gdcurl "${GD_API}/v1/domains?${q}" |
    jq '.[] | {domain: .domain, createdAt: .createdAt, expires: .expires, renewDeadline: .renewDeadline, status: .status}'
}

alias godaddy.list.renewable='godaddy.list statusGroups=RENEWABLE'
alias godaddy.list.inactive='godaddy.list statusGroups=INACTIVE'
alias godaddy.list.redemption='godaddy.list statuses=PENDING_HOLD_REDEMPTION'
